<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="领料单号" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="outsource_material_requisition" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="领料人员">
          <el-input v-model="formData.orderName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="领料日期">
          <el-date-picker
            v-model="formData.materialRequisitionTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="外协订单号" class="clickChoose" prop="outsourceOrderCode">
          <el-input v-model="formData.outsourceOrderCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseOrder"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="计划单号">
          <el-input v-model="formData.productionPlanCode" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="外协供应商">
          <el-input v-model="formData.supplierName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.url"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <!-- 订单明细 -->
        <div />
        <div v-if="materialName.length > 0" class="MaterialName">
          <span class="MaterialNameIcon el-icon-warning" />
          <div v-for="item in materialName" :key="item" class="MaterialNameName">
            <span>{{ item }}</span>
          </div>
          <div class="MaterialNameText">物料暂无库存，无法发货！</div>
        </div>
        <div v-else />
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add2">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="listData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
          :summary-method="getSummaries"
          show-summary
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" align="center" width="70" />
          <el-table-column label="领取数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="requisitionNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.requisitionNumber }}</span>
              <!-- <el-input v-model="scope.row.requisitionNumber" placeholder="请输入" /> -->
            </template>
          </el-table-column>
          <el-table-column label="物料编码" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="stockNum">
            <template slot-scope="scope">
              <span>{{ scope.row. stockNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="需求数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="needNumber">
            <template slot-scope="scope">
              <span>{{ scope.row. needNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="formData.automaticCreate == '1'" label="已领数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="hasRequisitionNumber">
            <template slot-scope="scope">
              <span>{{ scope.row. hasRequisitionNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="formData.automaticCreate == '1'" label="可领数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="hasRequisitionNumber">
            <template slot-scope="scope">
              <span>{{ scope.row. availableNumber }}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="formData.automaticCreate == '1'" label="实际领取数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="hasRequisitionNumber">
            <template slot-scope="scope">
              <span>{{ scope.row. hasRequisitionNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit('0')">保存</el-button>
      <el-button @click.stop="onSubmit('1')">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, getRawMaterialInfo } from '@/api/outsourceManage/outsourceReceiveMaterial'
import { detailList } from '@/api/outsourceManage/outsourceReturnMaterial'
import chooseOrder from './chooseOrder.vue'
import moment from 'moment'
import chooseMaterial from './chooseMaterial.vue'
import Big from 'big.js' // big.js解决精度丢失问题
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: '',
        code: '',
        materialRequisitionBy: '',
        orderName: '',
        materialRequisitionTime: '',
        automaticCreate: '0',
        outsourceOrderId: '',
        outsourceOrderCode: '',
        productionPlanCode: '',
        supplierName: '',
        fileName: '',
        fileRealName: '',
        url: '',
        remark: '',
        requisitionDetailList: [],
        status: '0'
      },
      rawData: [],
      listData: [],
      tableHeight: '',
      tableData1: [],
      tableData2: [],
      selectionsAll1: [],
      selectionsAll2: [],
      tableDefaultRow: null,
      materialName: [],
      rules: {
        code: [
          { required: true, message: '领料单号不能为空', trigger: 'change' }
        ],
        outsourceOrderCode: [
          { required: true, message: '外协订单号不能为空', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    listData() {
      if (this.listData.length > 7) {
        this.tableHeight = '390'
      } else {
        this.tableHeight = ''
      }
      this.$refs['table'].doLayout()
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['table'].doLayout()
    })
  },
  mounted() {
    if (this.id) { // 有id就是编辑
      this.getInfo()
    }
    this.formData.orderName = this.$store.state.user.name
    this.formData.materialRequisitionBy = this.$store.state.user.userId
    this.formData.materialRequisitionTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    setFileName(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.url = data[2]
    },
    headerCellClassName(data) {
      if (['requisitionNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    selectionChange2(rows) {
      this.selectionsAll2 = rows
    },
    // 物料不足名称数组去重
    materialNameArr(arr) {
      var newArr = arr.filter(function(item, index) {
        return arr.indexOf(item) === index // 因为indexOf 只能查找到第一个
      })
      return newArr
    },
    // 去除物料名称不足最后一位逗号
    Removecommas(arr) {
      const arrTemp = arr
      if (arrTemp.length > 0) {
        if (arrTemp.indexOf('等') != -1) {
          arrTemp[arrTemp.length - 2] = arrTemp[arrTemp.length - 2].substr(0, arrTemp[arrTemp.length - 2].length - 1)
        } else {
          //
          arrTemp[arrTemp.length - 1] = arrTemp[arrTemp.length - 1].substr(0, arrTemp[arrTemp.length - 1].length - 1)
        }
        this.materialName = arrTemp
      }
    },
    getList() {
      detailList({ outsourceOrderId: this.formData.outsourceOrderId }).then(res => {
        res.data.forEach(item => {
          item.handleId = item.id
          delete item.id
          delete item.remark
          item.requisitionNumber = '0'
        })
        this.materialName = []
        this.listData = []
        const data3 = []
        if (res.data.length > 0) {
          const data2 = this.$deepClone(res.data)
          data2.forEach(item => {
            if (item.stockNum == '0') {
              if (this.materialName.length < 5) {
                this.materialName.push(item.materialName + ',')
                this.materialName = this.materialNameArr(this.materialName)
              } else {
                this.materialName.push('等')
              }
            } else {
              data3.push(item)
            }
          })
          this.materialName = this.materialNameArr(this.materialName)
          this.Removecommas(this.materialName)
        }
        this.rawData = this.$deepClone(res.data)
        this.listData = this.mergeData(res.data)
        this.listData = this.listData.filter(item => item.stockNum !== '0')
      })
    },
    chooseOrderCallBack(data) {
      this.listData = []
      this.rawData = []
      this.formData.outsourceOrderId = data.id
      this.formData.outsourceOrderCode = data.code
      this.formData.supplierName = data.supplierName
      this.formData.productionPlanCode = data.productionPlanCode
      this.getList()
    },
    chooseOrder() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: this.formData.outsourceOrderId ? this.formData.outsourceOrderId : ''
          } // props
        },
        area: ['1320px', '700px'],
        title: '选择外协订单号', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => {
          this.formData[key] = res.data[key]
        })
        this.rawData = this.$deepClone(res.data.requisitionDetailList)
        this.listData = this.mergeData(res.data.requisitionDetailList)
        this.tableData = []
        this.materialName = []
        const arr = this.$deepClone(res.data.requisitionDetailList)
        // arr.forEach(ele => {
        //   if (ele.stockNum == '0') {
        //     if (this.materialName.length < 5) {
        //       this.materialName.push(ele.materialName + ',')
        //       this.materialName = this.materialNameArr(this.materialName)
        //     } else {
        //       this.materialName.push('等')
        //     }
        //   }
        //   ele.requisitionNumber = ele.needNumber
        //   delete ele.remark
        // })
        this.materialName = this.materialNameArr(this.materialName)
        this.Removecommas(this.materialName)
        this.listData = this.listData.filter(item => item.stockNum !== '0')
        console.log(this.listData, 'this.listData')
      })
    },
    getSummaries(param) {
      const {
        columns,
        data
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = '合计'
          return
        }
        switch (column.property) {
          case 'needNumber':
            sums[index] = data.map(item => item.needNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            break
        }
        switch (column.property) {
          case 'stockNum':
            sums[index] = data.map(item => item.stockNum).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            break
        }
        // switch (column.property) {
        //   case 'hasRequisitionNumber':
        //     sums[index] = data.map(item => item.hasRequisitionNumber).reduce((prev, curr) => {
        //       if (curr) {
        //         return new Big(prev).plus(curr).toString()
        //       } else {
        //         return new Big(prev).toString()
        //       }
        //     }, 0)
        //     break
        // }
        switch (column.property) {
          case 'requisitionNumber':
            sums[index] = data.map(item => item.requisitionNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            break
        }
      })
      return sums
    },
    // haveTwoDecimalPlaces(e, index) {
    //   if (e.indexOf('.') > -1) {
    //     const afterPoint = e.split('.')
    //     if (afterPoint[1].length > 2) {
    //       e = e.slice(0, e.indexOf('.') + 3)
    //       this.listData[index].requisitionNumber = e
    //       this.$message.warning('至多可输入两位小数')
    //     }
    //   }
    // },
    // 选择物料明细的回调
    showMaterial(data) {
      this.listData = this.mergeData(data)
      this.rawData = data
    },
    mergeData(data) {
      const resultMap = data.reduce((result, item) => {
        const { materialId, requisitionNumber, needNumber } = item
        if (!result[materialId]) {
          result[materialId] = { ...item }
        } else {
          result[materialId].requisitionNumber = (Number(result[materialId].requisitionNumber) + Number(requisitionNumber)).toString()
          result[materialId].needNumber = (Number(result[materialId].needNumber) + Number(needNumber)).toString()
        }
        return result
      }, {})

      return Object.values(resultMap)
    },
    onSubmit(num) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // if (this.listData.filter(item => !item.requisitionNumber).length > 0) {
          //   this.$message.warning('领取数量不能为空')
          //   return
          // } else if (this.listData.filter(item => Number(item.requisitionNumber) > Number(item.stockNum)).length > 0) {
          //   this.$message.warning('领取数量不能大于库存数量')
          //   return
          // } else if (this.listData.filter(item => item.requisitionNumber && !this.SETTINGS.reg_no_zero.test(item.requisitionNumber)).length > 0) {
          //   this.$message.warning('领取数量未正确填写')
          //   return
          // }
          if (this.rawData.filter(item => item.stockNum !== '0' && item.requisitionNumber == 0).length > 0 && num == '1') {
            this.$message.warning('领取数量不能为空')
            return
          }
          this.formData.requisitionDetailList = this.rawData
          if (this.formData.requisitionDetailList.length == 0 && num == '1') {
            this.$message.warning('领料明细不能为空')
            return
          }
          this.formData.status = num
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
      // console.log(this.tableData2)
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
      const listData = new Set(this.listData.map(item => item.materialId))
      this.rawData = this.rawData.filter(item => listData.has(item.materialId))
    },
    add2() {
      if (this.formData.outsourceOrderId) {
        this.$layer.iframe({
        // 弹框
          content: {
            content: chooseMaterial, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              orderId: this.formData.outsourceOrderId,
              selectedRow: this.rawData ? this.rawData : []
            } // props
          },
          area: ['1320px', '700px'],
          title: '选择物料', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      } else {
        this.$message.warning('请选择外协订单号')
        return
      }
    },
    remove2() {
      this.selectionsAll2.forEach(item => {
        this.tableData2.splice(this.tableData2.indexOf(item), 1)
      })
      // 找到 tableData2 里 isDefault 是 1 的 ，找到它的index
      if (this.tableData2.filter(item => item.isDefault == '1').length > 0) {
        this.tableDefaultRow = this.tableData2.indexOf(this.tableData2.filter(item => item.isDefault == '1')[0])
      } else { // 如果 isDefault 是 1 的 被删除了
        this.tableDefaultRow = '0'
      }
      this.chooseDefault(null, this.tableDefaultRow)
    },
    removeRow(row) {
      this.tableData.splice(this.tableData.indexOf(row), 1)
    },
    chooseDefault(row, currentIndex) {
      this.tableData2.forEach((ele, index) => {
        if (index == currentIndex) {
          ele.isDefault = '1'
        } else {
          ele.isDefault = '0'
        }
        return ele
      })
    }
  }
}
</script>

<style lang="less" scoped>
.table_container {
  padding-bottom: 20px !important;
  padding-top: 0px !important;
}
/deep/ .el-table__fixed-footer-wrapper {
  .el-table__cell:last-of-type {
    height: 39px !important;
  }
}
.MaterialName {
  display: flex;
  padding: 15px;
  flex: 1;
  color:rgb(244,156,31);
  text-align: center;
  font-size: 16px;
  align-items: center;
  margin-bottom: 3px;

  .MaterialNameIcon {
    padding: 2px 5px 0 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
